package cn.tworice.common.utils;

import cn.tworice.common.entity.dto.SendMailDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

@Component
@Slf4j
public class MailUtil {

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发送普通邮件
     * @author 二饭
     * @email 1786705138@qq.com
     */
    public void sendMail(SendMailDto sendMailDto){
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(new InternetAddress(MimeUtility.encodeText("二饭技术")+"<tworice_0811@163.com>").toString());
            message.setTo(sendMailDto.getTo());
            message.setSubject(sendMailDto.getSubject());
            message.setText(sendMailDto.getContent());


            this.mailSender.send(message);
            log.info("邮件已发送。");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送邮件时发生异常了！", e);
        }
    }

    /**
     * 发送HTML邮件
     * @author 二饭
     * @email 1786705138@qq.com
     */
//    public static void sendHTMLMail(SendMailDto sendMailDto) throws Exception{
//        MimeMessage message=mailSender.createMimeMessage();
//
//        try {
//            //true表示需要创建一个multipart message
//            MimeMessageHelper helper=new MimeMessageHelper(message,true);
//            helper.setFrom(new InternetAddress(MimeUtility.encodeText("二饭技术")+"<tworice_0811@163.com>"));
//            helper.setTo(sendMailDto.getTo());
//            helper.setSubject(sendMailDto.getSubject());
//            helper.setText(sendMailDto.getContent(),true);
//            mailSender.send(message);
//            log.info("发往-"+sendMailDto.getTo()+"-邮件已发送。");
//        }catch (Exception e) {
//            log.error("发往-"+sendMailDto.getTo()+"-邮件发送失败。");
//        }
//    }

//    public static void main(String[] args) throws Exception {
//
//        SendMailDto dto = new SendMailDto();
//        dto.setSubject("告警");
//        dto.setContent("您的亲友触发了一键报警按钮，请确认其是否安全。");
//        dto.setTo("1786705138@qq.com");
//        MailUtil.sendMail(dto);
//    }
}
